import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';

interface Position {
  row: number;
  col: number;
  isBackwardJump?: boolean;  // 添加这个属性来标记是否是往回吃
}

interface Piece {
  type: 1 | 2;  // 1: 白棋, 2: 黑棋
  isKing: boolean;
}

interface MoveRecord {
  from: Position;
  to: Position;
  captured?: Position;
}

@Component({
  selector: 'app-board',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './board.component.html',
  styleUrls: ['./board.component.less']
})
export class BoardComponent {
  board: (Piece | null)[][] = [];
  selectedPiece: Position | null = null;
  currentPlayer: 'white' | 'black' = 'white';
  possibleMoves: Position[] = [];
  forcedMoves: Position[] = []; // 新增：存储所有可以吃子的位置
  gameStatus: 'playing' | 'white_won' | 'black_won' = 'playing';
  moveHistory: MoveRecord[] = [];

  constructor() {
    this.initializeBoard();
    this.updateForcedMoves();
  }

  private initializeBoard() {
    this.board = Array(10).fill(null).map(() => Array(10).fill(null));
    
    // 放置白棋
    for (let row = 0; row < 4; row++) {
      for (let col = 0; col < 10; col++) {
        if ((row + col) % 2 === 1) {
          this.board[row][col] = { type: 1, isKing: false };
        }
      }
    }
    
    // 放置黑棋
    for (let row = 6; row < 10; row++) {
      for (let col = 0; col < 10; col++) {
        if ((row + col) % 2 === 1) {
          this.board[row][col] = { type: 2, isKing: false };
        }
      }
    }
  }

  onPieceClick(row: number, col: number) {
    if (this.gameStatus !== 'playing') return;

    if (!this.selectedPiece) {
      // 检查是否有必须吃子的情况
      const forcedJumps = this.getForcedJumps();
      if (forcedJumps.length > 0) {
        // 检查当前棋子是否可以吃子
        const canJump = this.getJumpMoves(row, col).length > 0;
        if (!canJump) return;
      }

      if (this.isValidSelection(row, col)) {
        this.selectedPiece = { row, col };
        this.possibleMoves = this.calculatePossibleMoves(row, col);
      }
    } else {
      const move = this.possibleMoves.find(m => m.row === row && m.col === col);
      if (move) {
        this.executeMove(this.selectedPiece, { row, col });
        this.checkForWinner();
      }
      this.selectedPiece = null;
      this.possibleMoves = [];
    }
  }

  private calculatePossibleMoves(row: number, col: number): Position[] {
    const piece = this.board[row][col];
    if (!piece) return [];

    // 检查是否有强制吃子的情况
    const forcedJumps = this.getForcedJumps();
    if (forcedJumps.length > 0) {
      // 如果当前棋子可以吃子，返回吃子着法
      const jumps = this.getJumpMoves(row, col);
      if (jumps.length > 0) {
        return jumps;
      }
      // 如果当前棋子不能吃子，但有其他棋子可以吃子，返回空数组
      return [];
    }

    // 如果没有强制吃子，返回所有可能的移动
    const moves: Position[] = [];
    if (piece.isKing) {
      this.addKingMoves(row, col, moves);
    } else {
      // 普通棋子只能向前移动一格
      const directions = piece.type === 1 ? [1] : [-1]; // 白棋向下，黑棋向上
      for (const rowDir of directions) {
        for (const colDir of [-1, 1]) {
          const newRow = row + rowDir;
          const newCol = col + colDir;
          if (this.isValidPosition(newRow, newCol) && !this.board[newRow][newCol]) {
            moves.push({ row: newRow, col: newCol });
          }
        }
      }
    }

    return moves;
  }

  private getJumpMoves(row: number, col: number): Position[] {
    const piece = this.board[row][col];
    if (!piece) return [];

    const moves: Position[] = [];
    const directions = [[1,1], [1,-1], [-1,1], [-1,-1]];

    for (const [rowDir, colDir] of directions) {
      const isBackward = (piece.type === 1 && rowDir < 0) || 
                        (piece.type === 2 && rowDir > 0);

      let currentRow = row + rowDir;
      let currentCol = col + colDir;
      
      while (this.isValidPosition(currentRow, currentCol)) {
        const targetPiece = this.board[currentRow][currentCol];
        if (!targetPiece) {
          if (piece.isKing) {
            currentRow += rowDir;
            currentCol += colDir;
            continue;
          }
          break;
        }
        
        if (targetPiece.type === piece.type) break;
        
        let jumpRow = currentRow + rowDir;
        let jumpCol = currentCol + colDir;
        
        while (this.isValidPosition(jumpRow, jumpCol) && !this.board[jumpRow][jumpCol]) {
          moves.push({ 
            row: jumpRow, 
            col: jumpCol,
            isBackwardJump: !piece.isKing && isBackward  // 标记往回吃的位置
          });
          if (!piece.isKing) break;
          jumpRow += rowDir;
          jumpCol += colDir;
        }
        break;
      }
    }

    return moves;
  }

  private addKingMoves(row: number, col: number, moves: Position[]) {
    const directions = [[1,1], [1,-1], [-1,1], [-1,-1]];
    
    for (const [rowDir, colDir] of directions) {
      let currentRow = row + rowDir;
      let currentCol = col + colDir;
      
      while (this.isValidPosition(currentRow, currentCol)) {
        if (this.board[currentRow][currentCol]) break;
        moves.push({ row: currentRow, col: currentCol });
        currentRow += rowDir;
        currentCol += colDir;
      }
    }
  }

  private executeMove(from: Position, to: Position) {
    const piece = this.board[from.row][from.col];
    if (!piece) return;

    const moveRecord: MoveRecord = { from: {...from}, to: {...to} };

    // 执行移动
    this.board[to.row][to.col] = piece;
    this.board[from.row][from.col] = null;

    // 检查是否吃子
    if (Math.abs(to.row - from.row) >= 2) {
      const rowDir = Math.sign(to.row - from.row);
      const colDir = Math.sign(to.col - from.col);
      let currentRow = from.row + rowDir;
      let currentCol = from.col + colDir;
      
      while (currentRow !== to.row || currentCol !== to.col) {
        if (this.board[currentRow][currentCol]) {
          this.board[currentRow][currentCol] = null;
          moveRecord.captured = { row: currentRow, col: currentCol };
        }
        currentRow += rowDir;
        currentCol += colDir;
      }

      // 检查是否可以继续吃子
      const furtherJumps = this.getJumpMoves(to.row, to.col);
      if (furtherJumps.length > 0) {
        this.selectedPiece = { row: to.row, col: to.col };
        this.possibleMoves = furtherJumps;
        this.forcedMoves = furtherJumps; // 更新强制移动，只显示当前棋子可以吃到的位置
        return; // 不切换玩家，继续吃子
      }
    }

    // 检查升王
    if (!piece.isKing && 
        ((piece.type === 1 && to.row === 9) || 
         (piece.type === 2 && to.row === 0))) {
      piece.isKing = true;
    }

    this.moveHistory.push(moveRecord);
    this.currentPlayer = this.currentPlayer === 'white' ? 'black' : 'white';
    this.updateForcedMoves();
  }

  private checkForWinner() {
    let whitePieces = 0;
    let blackPieces = 0;

    for (let row = 0; row < 10; row++) {
      for (let col = 0; col < 10; col++) {
        const piece = this.board[row][col];
        if (piece) {
          if (piece.type === 1) whitePieces++;
          else blackPieces++;
        }
      }
    }

    if (whitePieces === 0) this.gameStatus = 'black_won';
    if (blackPieces === 0) this.gameStatus = 'white_won';
  }

  undoLastMove() {
    const lastMove = this.moveHistory.pop();
    if (!lastMove) return;

    const { from, to, captured } = lastMove;
    this.board[from.row][from.col] = this.board[to.row][to.col];
    this.board[to.row][to.col] = null;

    if (captured) {
      this.board[captured.row][captured.col] = {
        type: this.currentPlayer === 'white' ? 2 : 1,
        isKing: false
      };
    }

    this.currentPlayer = this.currentPlayer === 'white' ? 'black' : 'white';
    this.gameStatus = 'playing';
  }

  private isValidPosition(row: number, col: number): boolean {
    return row >= 0 && row < 10 && col >= 0 && col < 10;
  }

  private isValidSelection(row: number, col: number): boolean {
    const piece = this.board[row][col];
    return piece !== null && 
           ((piece.type === 1 && this.currentPlayer === 'white') ||
            (piece.type === 2 && this.currentPlayer === 'black'));
  }

  isPossibleMove(row: number, col: number): boolean {
    return this.possibleMoves.some(move => move.row === row && move.col === col);
  }

  // 获取所有可以吃子的棋子位置
  private getForcedJumps(): Position[] {
    const forcedMoves: Position[] = [];
    
    for (let row = 0; row < 10; row++) {
      for (let col = 0; col < 10; col++) {
        const piece = this.board[row][col];
        if (piece && 
            ((piece.type === 1 && this.currentPlayer === 'white') ||
             (piece.type === 2 && this.currentPlayer === 'black'))) {
          // 获取这个棋子可以吃子后到达的位置
          const jumps = this.getJumpMoves(row, col);
          forcedMoves.push(...jumps);
        }
      }
    }
    
    return forcedMoves;
  }

  isBackwardJump(row: number, col: number): boolean {
    return this.possibleMoves.some(move => 
      move.row === row && 
      move.col === col && 
      move.isBackwardJump
    );
  }

  // 在每次移动后更新可吃子的位置
  private updateForcedMoves() {
    this.forcedMoves = [];
    for (let row = 0; row < 10; row++) {
      for (let col = 0; col < 10; col++) {
        const piece = this.board[row][col];
        if (piece && 
            ((piece.type === 1 && this.currentPlayer === 'white') ||
             (piece.type === 2 && this.currentPlayer === 'black'))) {
          // 只获取可以移动到的位置，不包括棋子本身的位置
          const jumps = this.getJumpMoves(row, col);
          if (jumps.length > 0) {
            // 只添加目标位置，不添加棋子位置
            this.forcedMoves.push(...jumps);
          }
        }
      }
    }
  }

  // 添加新方法检查是否是强制吃子位置
  isForcedMove(row: number, col: number): boolean {
    return !this.board[row][col] && // 只在空位置显示
           this.forcedMoves.some(move => move.row === row && move.col === col);
  }
}
